package com.lance.answer.gui.answer.gk.answer.lms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.HttpUtil;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * <p>学生点击所有的连接<p>
 * <p>
 * <p>
 * <p>
 * <p>
 * 工程经济,size:1
 *
 * @author : fengx
 * @since JDK8.0
 * create by fengx on 2021/7/15 14:47
 */
public class TestYiWangYiSaveVideo {


    public static final String JS = "var video = document.getElementsByTagName(\"video\");if(video.length>0){ video[0].src = \"https://jvod.300hu.com/vod/product/a7d50669-f57b-4da9-8cf8-43d04372cab0/0411e189a55b41cfada876041fa7fdd7.mp4?source=2&h265=h265/18799/d7d0ab77577f4ea0bcf5bc794316045a.mp4\";}";


    // static void watchVideo(WebDriver driver,String urlTask)throws Exception{
    public static void watchVideo(WebDriver driver, String JS) throws Exception {

        System.err.println("开始观看视频！！！！！！！！！");
        //    Util.switchToFirst(driver);
        // FIXME 当完成第一份形考任务时，必须提交，否则会弹出 ”是否保存当前页面“消息
        //  activityinstance.click();

        //延长加载时间
        Thread.sleep(5 * 1000);
        // Util.switchToUrl(driver,urlTask);
        Util.switchToLast(driver);
        Thread.sleep(2 * 1000);
        ((JavascriptExecutor) driver).executeScript(JS);
        Thread.sleep(2 * 1000);
//        List<WebElement> canvas = driver.findElements(By.tagName("canvas"));
//        //System.out.println("canvas大小");
//        //System.out.println(canvas.size());
//        for (WebElement player : canvas) {
//            //System.out.println("class是：" + player.getAttribute("class"));
//            if (player.getAttribute("class").startsWith("play")) {
//                //System.out.println("找到啦 ");
//                //System.out.println(player);
//                player.click();
//            } else {
//                continue;
//            }
//        }

        driver.findElement(By.cssSelector("button[class='mvp-toggle-play mvp-first-btn-margin']")).click();

        //   Thread.sleep(18000);
        Thread.sleep(18000);
        //FIXME    driver.navigate().back();
        //   driver.get("http://xinjiang.ouchn.cn/course/view.php?id=1967");
    }


    public static void main(String[] args) throws Exception {
        String driverPath = "c:\\ynouAutoStudy\\chromedriver.exe";
        ChromeDriver driver = Util.getDriver(driverPath);
        String url = "https://menhu.pt.ouchn.cn/site/ouchnPc/index";
        driver.get(url);
        Thread.sleep(3000);



        String userName = "1942001212871";
        String pwd = "Ouchn@2021";
        String subjectName = "习近平新时代中国特色社会主义思想";

        WebElement userNameInput = driver.findElement(By.id("loginName"));
        userNameInput.clear();
        userNameInput.sendKeys(userName);
        //TimeUnit.SECONDS.sleep(1);

        WebElement passwordInput = driver.findElement(By.id("password"));
        passwordInput.clear();
        passwordInput.sendKeys(pwd);
        //TimeUnit.SECONDS.sleep(1);

        // FIXME 要输入验证码
        Thread.sleep(10000);

        //webDriverWait.until(ExpectedConditions.elementToBeClickable(By.id("loginId"))).sendKeys(username);

        WebElement loginBtn = driver.findElement(By.name("button"));

        loginBtn.click();

        Thread.sleep(10000);


        // 在题库里获取答案

        String courseId = "14182";
        String videoId = "1508695";

        driver.get("https://lms.ouchn.cn/course/"+courseId+"/learning-activity/full-screen#/"+videoId);


//        watchVideo(driver,JS);
//
//          Thread.sleep(200000);

        Thread.sleep(10000);

        // Fixme 点击播放视频
        //  driver.findElement(By.cssSelector("button[class='mvp-toggle-play mvp-first-btn-margin']")).click();


        String postUrl = "https://lms.ouchn.cn/api/course/activities-read/"+videoId;

        String cookie = Util.getCookie(driver.manage().getCookies());


     //   String js = "document.getElementByClassName(\"mvp-play-progress\").setAttribute(\"style\",\"width: 97.5%;\")";
//        String js = "$('.mvp-play-progress').css('style','width: 20.5%;') ";
//
//        ((JavascriptExecutor) driver).executeScript(js);

        // https://www.cnblogs.com/du-hong/p/15337826.html
        Thread.sleep(2000);
        Actions action = new Actions(driver);
     //   WebElement target = driver.findElement(By.className("mvp-play-progress"));
      //  WebElement target = findElementByCssSelector(driver,"div[class='mvp-play-progress']",20);
        WebElement target = findElementByCssSelector(driver,"div[class='mvp-progress-control']",20);
     //   action.dragAndDropBy(target,1000,0);
       // action.contextClick(target).moveByOffset(990,0).perform();

     System.err.println("x:"+   target.getLocation().x);
     System.err.println("y:"+   target.getLocation().y);

     WebElement t1 = driver.findElement(By.cssSelector("button[class='mvp-play-rate-btn']"));
        System.err.println("t1x:"+   t1.getLocation().x);
        System.err.println("t1y:"+   t1.getLocation().y);

        action.contextClick(target).moveToElement(t1).perform();

        Thread.sleep(2000000);

        Map<String,String> heads = Maps.newHashMap();
        heads.put("referer","https://lms.ouchn.cn/course/"+courseId+"/learning-activity/full-screen");
        heads.put(":method","POST");
        heads.put(":authority","lms.ouchn.cn");
        heads.put("origin","https://lms.ouchn.cn");
        heads.put("cookie",cookie);
        heads.put(":path","/api/course/activities-read/"+videoId);

        // Map<String,Object> data   = Maps.newHashMap();
        JSONObject saveJson = new JSONObject();
        // 课程ID，固定的
     //   int videoLength = 449;
        String timeString = findElementByCssSelector(driver,"*[class='duration']",30).getText();

        int videoLength = getTime(timeString);
        int defaultStep = 60;
        int end = 0;
        while(end<videoLength){
            saveJson.put("start",end);
            saveJson.put("end", Math.min((end + defaultStep), videoLength));
            /**
             * result:{"activity_id":1507719,"activity_type":"learning_activity",
             * "completeness":"part","created_by_id":1382127,"created_for_id":1382127,
             * "data":{"completeness":23,"end":101,"ranges":[[0,101]]},
             * "id":68956656,"last_visited_at":"2022-04-16T04:52:25Z"}
             */
            /**
             * 程序的JSON
             * {"activity_id":1507719,"activity_type":"learning_activity",
             * "completeness":"part","created_by_id":1382127,"created_for_id":1382127,
             * "data":{"completeness":23,"end":101,"ranges":[[0,101]]},
             * "id":68956656,"last_visited_at":"2022-04-16T04:52:41Z"}
             */

            /**
             * 实际返回的JSON
             * {"activity_id":1507719,"activity_type":"learning_activity",
             * "completeness":"part","created_by_id":1382127,"created_for_id":1382127,
             * "data":{"completeness":47,"end":205,"ranges":[[0,205]]},
             * "id":68956656,"last_visited_at":"2022-04-16T04:54:35Z"}
             */

            /**
             * result:{"activity_id":1507719,"activity_type":"learning_activity","completeness":"part","created_by_id":1382127,"created_for_id":1382127,"data"
             * :{"completeness":47,"end":105,"ranges":[[0,205]]},"id":68956
             * 656,"last_visited_at":"2022-04-16T05:02:38Z"}
             */
            String result = HttpUtil.postJson(postUrl,saveJson,cookie,heads);
            System.err.println(result);
            YiWangYiVideoReturnInfo returnInfo = JSON.parseObject(result,YiWangYiVideoReturnInfo.class);
            end = returnInfo.getData().getEnd();
            Thread.sleep(5000);
        }


        driver.findElement(By.cssSelector("div[class='mvp-play-progress']"));
      //   doc.getElementsByClass("vp-play-progress").attr("style","width: 97.5%;");



        // 进入课程首页
        // div className = ouchnPc_index_course w
        // div className = ouchnPc_index_course_div

        for (WebElement we : driver.findElements(By.cssSelector("div[class='ouchnPc_index_course_div']"))) {
            String textContent = we.getText();
            System.err.println("text:" + textContent);
            if (textContent.contains(subjectName)) {
                we.findElement(By.tagName("a")).click();
                break;
            }
        }
        Util.switchToLast(driver);




        Thread.sleep(200000000);





//
    }





    /**
     * 将字符串的时间转成秒数
     * @param s 字符串时间 06：03
     * @return 秒数
     */
    public static int getTime(String s){
        int time = 0;
        try {
            String[] array = s.split(":");
            int i =array.length-1;
            for(String a:array){
                time += Math.pow(60,i)*Integer.parseInt(a);
                i--;
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return time;
    }



    private static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                });
    }

    public static List<WebElement> findElementsByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                }));
    }

    public static WebElement findElementByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<WebElement>)
                d -> {
                    assert d != null;
                    return d.findElement(By.cssSelector(cssSelector));
                }));
    }



}
